package config

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"os"
	"scoce_estimate/status"
)

const filename = "../config/config.json"

func init() {
	f, err := os.Open(filename)
	if err != nil {
		fmt.Println("找不到文件", filename)
		fmt.Println(err.Error())
		return
	}
	conf, err := ioutil.ReadAll(f)
	if err != nil {
		fmt.Println("读取时遇到错误")
		fmt.Println(err.Error())
		return
	}
	c := &Configuration{}
	err = json.Unmarshal(conf, c)
	if err != nil {
		fmt.Println("json格式错误")
		fmt.Println(err.Error())
		panic("json格式错误")
	}
	Cspj_title = c.Cspj_title
	Csps_title = c.Csps_title
	Cspj_map = c.Cspj_map
	Csps_map = c.Csps_map
	Cspj_file_path = c.Cspj_file_path
	Csps_file_path = c.Csps_file_path

	// config check
	for i := 0; i < len(Cspj_title); i++ {
		_, ok := Cspj_map[Cspj_title[i]]
		if !ok {
			panic("题目名称与题目编号不一致，problem titles inconsist with problem id.")
		}
	}
	for i := 0; i < len(Csps_title); i++ {
		_, ok := Csps_map[Csps_title[i]]
		if !ok {
			panic("题目名称与题目编号不一致，problem titles inconsist with problem id.")
		}
	}
	if len(Cspj_title) != len(Cspj_map) || len(Csps_title) != len(Csps_map) {
		panic("题目名称数量与题目编号数量不一致，problem titles amount inconsist with problem id amount.")
	}
}

// 无需修改，不影响
const Cspj_prefix string = "CSP-J-"
const Csps_prefix string = "CSP-S-"

type Configuration struct {
	Cspj_title     []string       `json:"cspj_title"`
	Csps_title     []string       `json:"csps_title"`
	Cspj_map       map[string]int `json:"cspj_map"`
	Csps_map       map[string]int `json:"csps_map"`
	Cspj_file_path string         `json:"cspj_file_path"`
	Csps_file_path string         `json:"csps_file_path"`
}

// CSP-J 题目对应题目编号
var Cspj_title []string
var Cspj_map map[string]int

// CSP-S 题目对应题目编号
var Csps_title []string
var Csps_map map[string]int

// 考生代码位置
var Cspj_file_path string
var Csps_file_path string

func GetTitleAndMap(level int) (titles []string, title_map map[string]int, fp string) {

	if level == status.CSPJ_LEVEL {
		titles = Cspj_title
		title_map = Cspj_map
		fp = Cspj_file_path
	} else if level == status.CSPS_LEVEL {
		titles = Csps_title
		title_map = Csps_map
		fp = Csps_file_path
	}
	return
}
